package com.pan.service.aspect;


import com.pan.dao.goodsPriceHistory.GoodsPriceHistoryDao;
import com.pan.dao.category.CategorySelectDao;
import com.pan.dao.category.CategoryUpdateDao;
import com.pan.dao.goods.GoodsSelectDao;
import com.pan.entity.Category;
import com.pan.entity.Goods;
import com.pan.entity.OperationGoodsPriceHistory;
import com.pan.entity.Result;
import com.pan.enume.ResultEnum;
import com.pan.excep.enume.ErrorCode;
import com.pan.excep.error.ServiceException;
import com.pan.tools.RedisTools;
import com.pan.vo.GoodsCreateVo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

@Aspect
@Component
public class GoodsAspect {


    @Resource
    private RedisTools redisTools;

    @Resource
    private CategoryUpdateDao categoryUpdateDao;

    @Resource
    private CategorySelectDao categorySelectDao;

    @Resource
    private GoodsPriceHistoryDao goodsPriceHistoryDao;

    @Resource
    private GoodsSelectDao goodsSelectDao;

    @Pointcut("execution(public * com.pan.service.impl.GoodsServiceImpl.insert(..))")
    public void insert(){}

    @Pointcut("execution(public * com.pan.service.impl.GoodsServiceImpl.update(..))")
    public void update(){}


    @Before("update() || insert()")
    @Order(1)
    public void checkLogin(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        String[] names = methodSignature.getParameterNames();
        int index = 0;
        for (int i=0;i<names.length;i++){
            if (names[i]=="adminTicket"){
                index = i ;
            }
        }
        String adminTicket = (String) joinPoint.getArgs()[index];

        Result<Boolean> isAdmin = redisTools.exists("admin:"+adminTicket);
        if (isAdmin == null||!isAdmin.getData()){
            throw new ServiceException(ErrorCode.NOT_LOGIN);
        }

    }

    @Order(2)
    @Around("update() && args(adminTicket,id,updateValue,updateMemberName)")
    public Result updateAround(ProceedingJoinPoint pjp, String adminTicket,Long id,Object updateValue,String updateMemberName){

        Goods goods = goodsSelectDao.selectById(id);
        if (goods==null){
            return new Result(ResultEnum.NOT_FOUND_ERROR);
        }
        if (((String)updateMemberName).equals("categoryId")){
            // pass 这里要检查一下 品类
            Category isCategory = categorySelectDao.selectById((Long) updateValue);
            if (isCategory==null){
                return new Result(403,"查无此品类",updateValue);
            }
            List<Category> liChild = categorySelectDao.selectByPid((Long) updateValue);
            if (liChild!=null||liChild.size()!=0){
                return new Result(403,"该拼了不是最终品类",updateValue);
            }
        }
        Result result = null;
        try {
            result = (Result) pjp.proceed();
            if (result!= null && result.getCode()==200 && ((String)updateMemberName).equals("price")){
                // pass 这里要记录价格变化
                OperationGoodsPriceHistory goodsPriceHistory = new OperationGoodsPriceHistory();
                goodsPriceHistory.setGoodsId(id);
                goodsPriceHistory.setPrice((Double) updateValue);
                Result resultAdminId = redisTools.hget("admin:"+adminTicket,"id");
                Long adminId = (Long) resultAdminId.getData();
                goodsPriceHistory.setAdminId(adminId);
                Timestamp nowTime = new Timestamp(System.currentTimeMillis());
                goodsPriceHistory.setUpdateDate(nowTime);
                goodsPriceHistoryDao.insert(goodsPriceHistory);
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return result;

    }

    @Order(2)
    @Around("insert() && args(adminTicket,goodsCreateVo)")
    public Result insertAround(ProceedingJoinPoint pjp,String adminTicket, GoodsCreateVo goodsCreateVo){
        Long categoryId = goodsCreateVo.getCategoryId();
        Category category = categorySelectDao.selectById(categoryId);
        if (category== null){
            throw new ServiceException(ErrorCode.NOT_FOUND);
        }
        Result result = null;
        try {
            result = (Result) pjp.proceed();
            if (result!=null&&result.getCode()==200){
                Integer productCount = category.getProductCount();
                categoryUpdateDao.updateProductCount(categoryId,productCount);

            }
        } catch (Throwable e) {
            throw new ServiceException(500,"com.pan.GoodsServiceImpl.insert() Around aspect 运行出错");
        }
        return result;
    }

}
